# -*- coding: utf-8 -*-
'''
author:Cooper
date:2012.4.23
公共类库
'''

__all__=['getConn','getURL','getRes','printJson','parseJsonField']

import md5
import time
import requests
import MySQLdb

domain='http://gw.api.taobao.com/router/rest'
app_secret='dd547d6090fd8973346d41f704a173db'
dkey={
    'app_key':'12543465',
    'sign_method':'md5',
    'v':'2.0'}
mysql_host='localhost'
mysql_user='root'
mysql_pw='LTS98'

def getConn(dbSet,charSet='utf8'):
    '''获取数据库连接'''
    db=None
    try:
        db=MySQLdb.connect(host=mysql_host,
            user=mysql_user,passwd=mysql_pw,
            db=dbSet,charset=charSet)
    except Exception as e:
        print e
    return db

def getURL(params):
    '''传入参数，生成请求URL'''
    timestamp=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    params['timestamp']=timestamp
    for key in dkey:
        params[key]=dkey[key]
    s=[key+params[key] for key in params]
    s.sort()
    s=app_secret+''.join(s)+app_secret
    sign=md5.new(s).hexdigest().upper()
    url=domain+'?sign='+sign
    for para in params:
        url=url+'&%s=%s'%(para,params[para])
    return url

def getRes(url,method='GET'):
    '''从URL获取返回对象'''
    tr=0
    r=None
    while 1:
        try:
            r=requests.request(method,url)
            break
        except Exception as e:
            tr+=1
            if tr==3:break
            pass
    return r

'''
def printJson(j):
    if isinstance(j,dict):
        for key in j:
            print key,
            if isinstance(j[key],dict):
                printJson(j[key])
            elif isinstance(j[key],list):
                print ' '.join(j[key])
            else:
                print j[key]
    elif isinstance(j,list):
        for li in j:
            if isinstance(li,list) or isinstance(li,dict):
                printJson(li)
            else:
                print li,
    else:
        print j
    pass
'''

def parseJsonField(j,field):
    '''从一段JSON数据中获取键值为field的JSON数据段'''
	jr=None
	for key in j:
		if key==field:
			jr=j[key]
		else:
			if isinstance(j[key],dict):
				jr=parseJsonField(j[key],field)
	return jr

def printJson(j,inden=0):
    '''打印JSON对象，可逐级缩进'''
    if isinstance(j,list):
        print ''
        for t in j:
            printJson(t,inden+1)
    elif isinstance(j,dict):
        print ''
        for k,v in j.items():
            print '  '*inden,k,
            printJson(v,inden+1)
    else:
        print '  '*inden,j


if __name__=='__main__':
    db=getConn('zhihu')
    db.close()
    del db
    r=getRes('http://www.sina.com')
    print r.status_code
    del r
    print 'The end...'